package com.jerry.token.controller;

import com.jerry.common.ResultStatus;
import com.jerry.common.constant.MediaTypes;
import com.jerry.common.utils.SecurityUtil;
import com.jerry.common.vo.ResultModel;
import com.jerry.token.TokenManager;
import com.jerry.token.model.TokenModel;
import com.jerry.user.entity.User;
import com.jerry.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Filename:    com.jerry.token.controller.TokenController
 * Description:
 * Copyright:   Copyright (c)2017
 * Company:     lngtop
 *
 * @author 谢余锋
 * @version 1.0
 *          Create at:   2017/3/13 下午1:26
 */
@RestController
@RequestMapping("/token")
public class TokenController {

    @Autowired
    private UserService userService;

    @Autowired
    private TokenManager tokenManager;

    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public ResultModel login(@RequestBody User user) {
        User dbUser = userService.queryByUsername(user.getUsername());
        if (dbUser != null && SecurityUtil.checkpw(user.getPassword(), dbUser.getPassword())) {
            TokenModel model = tokenManager.createToken(dbUser.getId(), user.getUsername());
            return new ResultModel(ResultStatus.SUCCESS.getCode(), "", model);
        } else {
            return ResultModel.error(ResultStatus.USER_NOT_FOUND);
        }
    }

    @RequestMapping(value = "getByToken", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResultModel getByToken(@RequestParam String token) {
        TokenModel tokenModel = tokenManager.checkToken(token);
        return ResultModel.success(tokenModel);
    }
}
